import { useEffect, useState, useRef } from "react";
import { type Device } from "react-native-ble-plx";
import Spinner from "react-native-loading-spinner-overlay";
import Dialog from "react-native-dialog";
import {
  ScrollView,
  View,
  Image,
  Text,
  StyleSheet,
  TouchableOpacity,
} from "react-native";
import { getStorageData, setStorageData, determineCurrentDevice } from "utils";
import { manager } from "utils/bleManage";
import toast from "utils/toast";
import BaseDialog from "components/BaseDialog";
import translate from "utils/translate";
const Buffer = require("@craftzdog/react-native-buffer").Buffer;

export default ({ navigation }: RootStackScreenProps) => {
  const [bleList, setBleList] = useState<Device[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const inactiveList = useRef<string[]>([]);
  const [value, setValue] = useState("");
  const [innerModalVisible, setInnerModalVisible] = useState(false);
  const bindList = useRef<BindDevice[]>([]);
  const currentDevice = useRef<BindDevice>();
  const onConnect = (device: Device) => {
    manager
      .connectToDevice(device.id)
      .then((device) => {
        inactiveList.current = [...inactiveList.current, device.id];
        manager
          .discoverAllServicesAndCharacteristicsForDevice(device.id)
          .then((device) => {
            device
              .services()
              .then(async (services) => {
                const item = determineCurrentDevice(services);
                if (item) {
                  const characteristicsList = await item.characteristics();
                  for (let current of characteristicsList) {
                    if (
                      current.isWritableWithResponse &&
                      current.isNotifiable
                    ) {
                      current
                        .writeWithoutResponse(
                          Buffer.from("A3", "hex").toString("base64")
                        )
                        .then(() => {
                          setLoading(false);
                          const hasDeviceId = bindList.current.some((item) => {
                            return item.uuid == device.id;
                          });
                          if (hasDeviceId) {
                            toast(translate("main.bindTip1"));
                            navigation.replace("index", {});
                          } else {
                            const { id, name } = device;
                            setModalVisible(true);
                            currentDevice.current = {
                              uuid: id,
                              name: name ?? "",
                            };
                          }
                        });
                      // const Subscription = current.monitor(
                      //   (err, characteristic) => {
                      //     if (err && err.reason) {
                      //       // toast(err.reason, 5 * 1000);
                      //       setLoading(false);
                      //       return Subscription.remove();
                      //     }
                      //     if (characteristic?.value) {
                      //       setLoading(false);
                      //       const hasDeviceId = bindList.current.some(
                      //         (item) => {
                      //           return item.uuid === device.id;
                      //         }
                      //       );
                      //       if (hasDeviceId) {
                      //         toast("已绑定此设备");
                      //         navigation.replace("bind", {});
                      //       } else {
                      //         const { id, name } = device;
                      //         setModalVisible(true);
                      //         currentDevice.current = {
                      //           uuid: id,
                      //           name: name ?? "",
                      //         };
                      //       }
                      //     }
                      //     return Subscription.remove();
                      //   }
                      // );
                      // return current.writeWithResponse(
                      //   Buffer.from("A3", "hex").toString("base64")
                      // );
                    }
                    // else {
                    //   setLoading(false);
                    //   ToastAndroid.showWithGravity(
                    //     "设备非法或者没有发现可用的特征值",
                    //     5 * 1000,
                    //     ToastAndroid.CENTER
                    //   );
                    // }
                  }
                } else {
                  setLoading(false);
                  toast(translate("main.error"));
                }
              })
              .catch(() => {
                setLoading(false);
                toast(translate("main.error"));
              });
          });
      })
      .catch(() => {
        setLoading(false);
        toast(translate("main.error"));
      });
  };
  useEffect(() => {
    getStorageData("deviceList").then((value) => {
      setBleList(value ? JSON.parse(value) : []);
    });
    getStorageData("bleList").then((value) => {
      bindList.current = value ? JSON.parse(value) : [];
    });
    return () => {
      for (let deviceId of inactiveList.current) {
        manager.cancelDeviceConnection(deviceId);
      }
    };
  }, []);
  const handleCancel = () => {
    setModalVisible(false);
    manager
      .cancelDeviceConnection(currentDevice.current?.uuid as string)
      .then((device) => {
        if (device) {
          inactiveList.current.splice(
            inactiveList.current.findIndex(
              (item) => item === currentDevice.current?.uuid
            ),
            1
          );
        }
      });
  };
  return (
    <>
      <View
        style={{
          flex: 1,
        }}
      >
        <Spinner
          visible={loading}
          textContent={translate("main.loading") + "..."}
          textStyle={{
            color: "rgba(10, 89, 247, .8)",
          }}
          color="rgba(10, 89, 247, .8)"
          cancelable
        />
        <ScrollView
          style={{
            flex: 1,
            backgroundColor: "#fff",
          }}
        >
          <View style={{ alignItems: "center" }}>
            {bleList.map((item) => {
              return (
                <View
                  key={item.id}
                  style={{
                    flexDirection: "row",
                    alignItems: "center",
                    justifyContent: "space-between",
                    width: "90%",
                    borderBottomColor: "#f9f9f9",
                    borderBottomWidth: 1,
                  }}
                >
                  <View style={{ flexDirection: "row", alignItems: "center" }}>
                    <Image
                      style={styles.image}
                      source={require("../../assets/images/ble.png")}
                    ></Image>
                    <Text>{item.name}</Text>
                  </View>
                  <TouchableOpacity
                    style={{
                      flexDirection: "row",
                      alignItems: "center",
                    }}
                    onPress={() => {
                      if (inactiveList.current.includes(item.id ?? "")) return;
                      onConnect(item);
                    }}
                  >
                    <Text
                      style={{
                        color: inactiveList.current.includes(item.id ?? "")
                          ? "rgba(10, 89, 247, .8)"
                          : undefined,
                      }}
                    >
                      {inactiveList.current.includes(item.id ?? "")
                        ? translate("home.bind.Connected")
                        : translate("home.bind.unconnected")}
                    </Text>
                    <Image
                      style={{
                        width: 24,
                        height: 24,
                        marginLeft: 12,
                      }}
                      source={require("../../assets/images/arrow-right-bold.png")}
                    ></Image>
                  </TouchableOpacity>
                </View>
              );
            })}
          </View>
        </ScrollView>
      </View>
      <BaseDialog
        visible={modalVisible}
        content={translate("main.bindContent")}
        handleCancel={handleCancel}
        handleSubmit={() => {
          setModalVisible(false);
          setInnerModalVisible(true);
        }}
      ></BaseDialog>
      <BaseDialog
        visible={innerModalVisible}
        title={translate("main.bind")}
        handleCancel={handleCancel}
        needCancel={false}
        handleSubmit={() => {
          if (value) {
            const { name, ...rest } = currentDevice.current as BindDevice;
            bindList.current.unshift({
              name: value,
              ...rest,
            });
            setStorageData("bleList", JSON.stringify(bindList.current)).then(
              () => {
                toast(translate("main.success"));
                setInnerModalVisible(false);
                navigation.navigate("index", {});
              }
            );
          } else {
            toast(translate("main.labelError"));
          }
        }}
      >
        <Dialog.Input
          autoFocus
          onChangeText={setValue}
          value={value}
          label={translate("main.name")}
        ></Dialog.Input>
      </BaseDialog>
    </>
  );
};
const styles = StyleSheet.create({
  image: {
    width: 60,
    height: 67,
  },
});
